package com.naiterui.ehp.bs.b2c.common.interceptor;

import com.naiterui.ehp.bp.support.security.HeaderConstant;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.naiterui.ehp.bp.support.context.ResourceHolder;
import com.naiterui.ehp.bs.b2c.common.util.UserUtils;
import com.naiterui.ehp.bs.b2c.common.vo.UserVO;

/**
 * @author guoyongxiang
 * @date 2019-05-13 20:57
 * @since 1.0.0
 */
@Slf4j
public class UserInterceptior implements HandlerInterceptor {

    private static final String PATIENT_ID = "patientId";
    private static final String DOCTOR_ID = "doctorId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String origin = request.getHeader(HeaderConstant.HEADER_ORIGIN);
        if (!String.valueOf(HeaderConstant.HEADER_ORIGIN_PATIENT_APP).equals(origin)) {
            UserVO userVO = new UserVO();
            String patientId = request.getHeader(PATIENT_ID);
            String doctorId = request.getHeader(DOCTOR_ID);

            if (StringUtils.isEmpty(patientId)) {
                patientId = request.getParameter(PATIENT_ID);
            }

            if (StringUtils.isEmpty(doctorId)) {
                doctorId = request.getParameter(DOCTOR_ID);
            }
            userVO.setDoctorId(!StringUtils.isEmpty(doctorId) ? Long.valueOf(doctorId) : null);
            userVO.setPatientId(!StringUtils.isEmpty(patientId) ? Long.valueOf(patientId) : null);
            log.info("资源持有器线程上下文-存入数据-B2C-UserInterceptior patientId {}", patientId);
            ResourceHolder.bindResource(UserUtils.REQ_USER, userVO);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ResourceHolder.clear();
    }
}
